//
//  RankView.m
//  SoundPill
//
//  Created by 宋旭东 on 15/10/20.
//  Copyright © 2015年 宋旭东. All rights reserved.
//

#import "RankView.h"

@interface RankView ()<MJRefreshBaseViewDelegate,UITableViewDelegate, UITableViewDataSource>
{
    int page;
    int lastPage;
    int pages;
    NSString *_filePath;
    MJRefreshHeaderView *header;
    MJRefreshFooterView *fotter;
}
@property (assign, nonatomic) NSInteger index;
@end

@implementation RankView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRelation:) name:@"reloadRelation" object:nil];
        self.rankArray = [NSMutableArray array];
        [self createTabelView];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"personRank"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadRankDataWithResponseObject:content pag:1];
            page = 1;
        } else {
            [header beginRefreshing];
        }
    }
    return self;
}
-(void)reloadRelation:(NSNotification *)notification
{
    NSDictionary *dict = notification.object;
    if (_rankArray.count > 0) {
        
        Rank *rankModel = _rankArray[_index];
    if ([[[dict valueForKey:@"data"] valueForKey:@"id"] isEqualToString:rankModel.id]) {
        if ([[[dict valueForKey:@"meta"] valueForKey:@"following"] boolValue] == NO) {
            rankModel.follow = @"0";
            [_rankArray replaceObjectAtIndex:_index withObject:rankModel];
            [_tableView reloadData];
        } else {
            if ([[[dict valueForKey:@"meta"] valueForKey:@"followed"] boolValue] == YES) {
                rankModel.follow = @"2";
                [_rankArray replaceObjectAtIndex:_index withObject:rankModel];
                [_tableView reloadData];
            } else {
                rankModel.follow = @"1";
                [_rankArray replaceObjectAtIndex:_index withObject:rankModel];
                [_tableView reloadData];
            }
        }
    }
    }
}
- (void)createTabelView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorColor:[UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000]];
    [self addSubview:self.tableView];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    header = [MJRefreshHeaderView header];
    header.scrollView = _tableView;
    header.delegate = self;
    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _tableView;
    fotter.delegate = self;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark -- cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.frame.size.height / 8;
}

#pragma mark -- cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _rankArray.count;
}

#pragma mark -- 重用池
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"reuse";
    RankTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[RankTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_rankArray.count > 0) {
        cell.rankModel = _rankArray[indexPath.row];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.index = indexPath.row;
    
    Rank *rankModel = _rankArray[indexPath.row];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:rankModel.id forKey:@"othersUserID"];
    [userDefaults synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoUser" object:rankModel.id];
}
- (void)requestData:(int)pag Refreshing:(MJRefreshBaseView *)refreshView
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/rank?p=%d", pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadRankDataWithResponseObject:responseObject pag:pag];
        [refreshView endRefreshing];
        if (pag == 1) {
            //            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [refreshView endRefreshing];
    }];
  
}
- (void)reloadRankDataWithResponseObject:(id)responseObject pag:(int)pag
{
    NSDictionary *data = [responseObject objectForKey:@"data"];
    for (NSDictionary *dic in data) {
        Rank *model = [[Rank alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [_rankArray addObject:model];
    }
    NSDictionary *meta = [responseObject valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            fotter.hidden = YES;
        }
    }
    if (_rankArray.count > 0) {
        [_tableView reloadData];
    }
}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //    NSLog(@"%@----开始进入刷新状态", refreshView.class);
    
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [fotter endRefreshing];
        [_rankArray removeAllObjects];
        [self requestData:page Refreshing:refreshView];
    }else {
        // 上拉加载更多
        if (pages == 1 || page == pages) {
            fotter.hidden = YES;
        } else {
            page++;
            [self requestData:page Refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    //    NSLog(@"%@----刷新完毕", refreshView.class);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
